package day14.KeJian;

public class MyRunnable03 implements Runnable{
    private static int ticketCount = 100;
    @Override
    public void run() {
        while (true){
            if ("窗口1".equals(Thread.currentThread().getName())){
                boolean result = synchronizedMthod();
                if (result){
                    break;
                }
            }
            if ("窗口2".equals(Thread.currentThread().getName())){
                synchronized (MyRunnable03.class){
                    if (ticketCount == 0){
                        break;
                    }else {
                        try {Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
                    }
                }
            }
        }
    }
    private static synchronized boolean synchronizedMthod(){
        if (ticketCount ==0 ){
            return  true;
        }else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + ticketCount + "张票");
            return false;
        }
    }
}
class Demo04{
    public static void main(String[] args) {
        MyRunnable03 mr3 = new MyRunnable03();

        Thread t1 = new Thread(mr3);
        Thread t2 = new Thread(mr3);

        t1.setName("窗口一");
        t1.setName("窗口二");

        t1.start();
        t2.start();
    }

}